package com.gem.talkbase.activity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import org.jivesoftware.smack.packet.Presence;
import org.json.JSONException;
import org.json.JSONObject;
import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import com.gem.talkbase.R;
import com.gem.talkbase.R.drawable;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.constant.Constants;
import com.gem.talkbase.fragment.Fragment_message;
import com.gem.talkbase.service.JSON_Friend_info;
import com.gem.talkbase.util.RotationHelper;
import com.gem.talkbase.util.XmppTool;

import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
//=====================================注册activity==============================
@SuppressLint("CommitPrefEdits")
public class RegisterActivity extends FinalActivity {

	static boolean flag=false;
	RotationHelper rotateHelper; 
	public ViewGroup mSecondContainer; 
	EditText phoneNumber,pass,upass;
	static String phoneNum,pass1,pass2;
	Button Register;
	String requestPath=Client.Register_URL;
	String requestPath1=Client.Register_URL1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.register);
		phoneNumber = (EditText) findViewById(R.id.register_edit);  
		pass = (EditText) findViewById(R.id.code_edit);
		upass =(EditText) findViewById(R.id.code_edit2);
		Register =(Button) findViewById(R.id.register_button1);
		Button left_btn = (Button) findViewById(R.id.left_btn); 
	

		//手机号监听
		phoneNumber.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				fun();
			}
		});

		//重复密码监听
		upass.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				if(hasFocus && pass.getText().toString().trim().equals("")){//如果组件获得焦点
					Toast toast = Toast.makeText(RegisterActivity.this, "密码不能为空，请输入密码！", Toast.LENGTH_SHORT); 
					toast.show();
				}
			}
			
		});
		// 注册
		Register.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				pass1=pass.getText().toString();
				pass2=upass.getText().toString();
				phoneNum = RegisterActivity.this.phoneNumber.getText().toString();
				if( !pass1.equals(pass2)){
					Toast toast = Toast.makeText(RegisterActivity.this, "两次输入密码不一致，请重新输入！", Toast.LENGTH_SHORT); 
					toast.show();
					
				}
				else if(fun()){
					
					AjaxParams params = new AjaxParams();
					params.put("username", phoneNum);  
					params.put("password1", pass1);
					params.put("password2", pass2);
					FinalHttp fh = new FinalHttp();  
					fh.post(requestPath1, params, new AjaxCallBack<String>() {  
						@Override
						public void onFailure(Throwable t, String strMsg) {
							System.out.println("2加载失败！！！");  
							super.onFailure(t, strMsg);
						}  

						@Override 
						public void onLoading(long count, long current) {
							// TODO Auto-generated method stub
							System.out.println("2正在加载！！！");
							super.onLoading(count, current);
						}
						public void onSuccess(String jsonString) {
							super.onSuccess(jsonString);
							System.out.println("2加载成功");
						if(jsonString.toString().length()==2){
							System.out.println("2验证返回");
						}
						else{
							System.out.println("11111111111111111111111111111111111111111111111111");
							Thread t=new Thread(new Runnable() {	 		  	
								public void run() {	
									try {
										System.out.println("22222222222222222222222222222222222222222222");
										System.out.println(phoneNum+"============="+pass1);
										//登录第三方服务器==============================
										XmppTool.getConnection().login(phoneNum, pass1);
										System.out.println("333333333333333333333333333333333333333333333333");
										//System.out.println(username+"())()()()()()()()"+password);
										Presence presence = new Presence(Presence.Type.available);
										XmppTool.getConnection().sendPacket(presence);
										System.out.println("1111111111111=======================================");
										Intent service = new Intent(RegisterActivity.this,ChatMessageService.class);
										startService(service);
										System.out.println("2222222222222=======================================");
										Intent intent =new Intent(RegisterActivity.this,MainActivity.class);
										intent.putExtra("username",phoneNum);
										startActivity(intent);
										
										SharedPreferences sharedPreferences1 = getSharedPreferences(Client.RGISTER_STRING, MODE_PRIVATE); 
										Editor editor = sharedPreferences1.edit();//获取编辑器 
										editor.putString("user_id", phoneNum);  //注册电话
										editor.commit();//提交修改 ==================================
										
										RegisterActivity.this.finish();
									} catch (Exception e) { 
										//    XmppTool.closeConnection();
										e.printStackTrace();
									}finally{
									
									}
								}
							});
							t.start();
						}
						}
					});
					
				}
				else{
					Toast.makeText(RegisterActivity.this, "请检查您的注册信息", Toast.LENGTH_LONG);
				}
						


			}


		});
		
		
		
	
		//===========================返回按钮监控旋转=======================================
		left_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {		 
				mSecondContainer = (LinearLayout) findViewById(R.id.layout_register);  
				mSecondContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
				rotateHelper = new RotationHelper(RegisterActivity.this,Constants.KEY_SECOND_CLOCKWISE);//4  
				rotateHelper.applyFirstRotation(mSecondContainer,0, 92); //0-->92 
			}
		});
		
	}
	public void jumpToFirst() {
		
		Intent in = new Intent();  
		in.setClass(RegisterActivity.this, LoginActivity.class);  
		Bundle bundle = new Bundle();  
		bundle.putString("second", "Second");  
		in.putExtras(bundle);  
		startActivity(in);  
		overridePendingTransition(R.anim.fade, R.anim.hold); 
	}
	
	public boolean fun(){
		phoneNum = RegisterActivity.this.phoneNumber.getText().toString();
		if(phoneNumber.getText().toString().trim().length() == 0){
	          Toast.makeText(RegisterActivity.this, "请先输入您的手机号", Toast.LENGTH_LONG).show();
			}
		 else if(phoneNumber.getText().toString().trim().length() == 11&&(phoneNum.trim().matches("^1[358]\\d{9}$"))){
			
			AjaxParams params = new AjaxParams();
			  params.put("username", phoneNum);
				  FinalHttp fh = new FinalHttp();

			  fh.post(requestPath, params, new AjaxCallBack<String>(){
				  @Override
					public void onFailure(Throwable t, String strMsg) {
						System.out.println("1加载失败！！！");
						super.onFailure(t, strMsg);
					}
			        @Override
			        public void onLoading(long count, long current) {
			        	super.onLoading(count, current);
			        }

			        public void onSuccess(String jsonString) {
			        	super.onSuccess(jsonString);
			        	if(jsonString.toString().length()==2){
			        		Toast.makeText(RegisterActivity.this, "该用户已存在", Toast.LENGTH_SHORT).show();
			        	}
			        	else{
			        		flag=true;
			        		//Toast.makeText(RegisterActivity.this, "用户名注册成功", Toast.LENGTH_SHORT).show();
			        	}
			        }
			  });



		} 
		else{
			 Toast.makeText(RegisterActivity.this, "请检查您的手机号", Toast.LENGTH_SHORT).show();
		}
		
		
		return flag;
		
	}


	}
	
	
	
	



